import { Layout, Menu, Button, Space } from 'antd';
import { UserOutlined, FileTextOutlined, LogoutOutlined } from '@ant-design/icons';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { useState, useEffect } from 'react';
import { auth } from '../utils/auth';

const { Header, Sider, Content } = Layout;

export default function MainLayout() {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedKey, setSelectedKey] = useState('1');

  useEffect(() => {
    // 根据当前路径设置选中的菜单项
    if (location.pathname.includes('/users')) {
      setSelectedKey('1');
    } else if (location.pathname.includes('/cases')) {
      setSelectedKey('2');
    }
  }, [location]);

  const handleLogout = () => {
    auth.logout();
    navigate('/login');
  };

  const menuItems = [
    {
      key: '1',
      icon: <UserOutlined />,
      label: '用户管理',
      onClick: () => navigate('/users'),
    },
    {
      key: '2',
      icon: <FileTextOutlined />,
      label: '案例管理',
      onClick: () => navigate('/cases'),
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh', width: '100vw' }}>
      <Sider collapsible collapsed={collapsed} onCollapse={(value) => setCollapsed(value)}>
        <div style={{ 
          textAlign: 'center', 
          padding: '20px 0', 
          color: '#fff',
          fontSize: collapsed ? '16px' : '18px',
          fontWeight: 'bold'
        }}>
          {collapsed ? '管理' : '管理系统'}
        </div>
        <Menu 
          theme="dark" 
          mode="inline" 
          selectedKeys={[selectedKey]}
          items={menuItems}
        />
      </Sider>
      <Layout>
        <Header style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          background: '#fff',
          padding: '0 24px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <div style={{ fontSize: '18px', fontWeight: 'bold' }}>
            寰界致造管理后台
          </div>
          <Space>
            <span style={{ color: '#666' }}>欢迎，{auth.getCurrentUser()}</span>
            <Button 
              icon={<LogoutOutlined />} 
              onClick={handleLogout}
              danger
            >
              退出登录
            </Button>
          </Space>
        </Header>
        <Content style={{ margin: '24px 16px', padding: 24, background: '#fff', minHeight: 280 }}>
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
}